/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(TreeNode*& root, vector<int>& nums, int l, int r) {
        if (l > r)
            return nullptr;
        int mid = (l + r) / 2;
        if (root == nullptr) {
            root = new TreeNode(nums[mid]);
            root->left = build(root, nums, l, mid - 1);
            root->right = build(root, nums, mid + 1, r);
            return root;
        }
        TreeNode* newnode = new TreeNode(nums[mid]);
        if (root->val > nums[mid])
            root->left = newnode;
        else
            root->right = newnode;

        newnode->left = build(newnode, nums, l, mid - 1);
        newnode->right = build(newnode, nums, mid + 1, r);

        return newnode;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int sz = nums.size();
        TreeNode* root = nullptr;
        build(root, nums, 0, sz - 1);
        return root;
    }
};